package com.logic.view

import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.jakewharton.rxbinding3.view.clicks
import com.logic.contract.StockInRfidContract
import com.logic.presenter.StockInRfidPresenter
import com.sinopec.basemodule.dialog.dfHint
import com.sinopec.basemodule.launchcontract.ErrorPalletCodesResultLaunch
import com.sinopec.basemodule.launchcontract.UHFInResultLaunch
import com.sinopec.basemodule.model.ErrorPalletCodeResultModel
import com.sinopec.basemodule.model.ErrorPalletCodesResultModel
import com.sinopec.basemodule.model.StockInApiRequestModel
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.basemodule.utils.kotlin.annotation.Style
import com.sinopec.basemodule.utils.kotlin.bean.TextMoreStyle
import com.sinopec.basemodule.utils.kotlin.setMoreStyle
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.bm_a_uhf.*
import java.util.concurrent.TimeUnit

/**
 * @author lwj
 * @ClassName: UhfInActivity
 * @Description: 入库-rfid扫码界面
 */
@Route(path = ARouterManagerUtils.GOTO_UHF_IN_ACTIVITY)
class UhfInActivity : BaseUhfActivity<StockInRfidPresenter>(
    "入库扫码"
), StockInRfidContract.View {

    /**
     * 带出的参数
     */
    private val params by lazy {
        UHFInResultLaunch.getParams(this)
    }

    //当前已扫所有编码集合
    var allPalletCodes: List<String> = arrayListOf()

    //错误编码集合
    var errorPalletCodes: List<ErrorPalletCodeResultModel> = arrayListOf()

    //已经落库的有效编码
    var validCodeList = ArrayList<String>()

    /**
     * 错误托盘校验结果界面启动器
     */
    private val errorPalletCodesResultLaunch by lazy {
        registerForActivityResult(ErrorPalletCodesResultLaunch) { isTrue ->
            if (isTrue != null && isTrue) {
                //移除错误的编码，留下正确的编码
                val newList = ArrayList<String>()
                val errorCodeList = errorPalletCodes.map { it.palletCode }
                allPalletCodes.forEach {
                    val isHave = errorCodeList.contains(it)
                    if (!isHave) {
                        newList.add(it)
                    }
                }
                uhfKernel.scan.clear()
                normalList = newList
                uhfKernel.data.onRefreshData(newList)
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mPresenter = StockInRfidPresenter(this)
        //已经落库的有效编码
        validCodeList = (params?.palletCodes ?: ArrayList()) as ArrayList<String>
        //是否显示顶部查看编码布局
        ll_change_number.visibility = if (validCodeList.size != 0) View.VISIBLE else View.GONE
        ll_look.visibility = View.VISIBLE
        tv_look.paintFlags = tv_look.paintFlags or Paint.UNDERLINE_TEXT_FLAG

        tv_change_number.setMoreStyle(
            TextMoreStyle.builder(
                "本单已入库有效编码"
            ).setTextColor(
                Color.parseColor("#002344")
            ).setTextStyle(
                Style.NORMAL
            ).build(),

            TextMoreStyle.builder(" ${validCodeList.size} ").setTextColor(
                Color.parseColor("#6e85f9")
            ).setTextStyle(Style.BOLD)
                .build(),

            TextMoreStyle.builder(
                "块"
            ).setTextColor(
                Color.parseColor("#002344")
            ).setTextStyle(
                Style.NORMAL
            ).build(),
        )
    }

    override fun initEvent() {
        super.initEvent()

        /**
         * 错误托盘校验结果界面启动器
         */
        errorPalletCodesResultLaunch

        /**
         * 查看已读有效编码
         */
        addDisposable(ll_look
            .clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                ARouterManagerUtils.gotoNormalCodeListActivity(mContext,
                    params?.palletCodes as ArrayList<String>)
            })

    }

    override fun onAccessRefreshList(
        sourceList: List<String>?,
        targetList: ArrayList<String>,
    ): Boolean {
        if (sourceList?.size == 0) {
            targetList.clear()
            return true
        }
        targetList.clear()
        if (sourceList != null && sourceList.isNotEmpty()) {
            for (i in sourceList.indices) {
                val operateTagMap = sourceList[i]
                //过滤已读有效编码
                if (!validCodeList.contains(operateTagMap)) {
                    targetList.add(operateTagMap)
                }
            }
        }

        return true
    }

    override fun dispatchNextStep(mList: ArrayList<String>) {
        dfHint(buildString {
            append("本次共扫码<font color='#6e85f9'>${mList.size}</font>块，")
            append("是否确认入库？")
        }) {
            if (it) {
                val requestModel = StockInApiRequestModel()
                requestModel.taskRecordId = params?.taskRecordId
                requestModel.palletCodes = mList
                mPresenter.confirmStockIn(requestModel)
            }
        }.show(supportFragmentManager, "")
    }

    override fun confirmStockInSuccess(
        allList: List<String>?,
        errorList: List<ErrorPalletCodeResultModel>?,
    ) {
        if (!errorList.isNullOrEmpty()) {
            val resultModel = ErrorPalletCodesResultModel()
            this.allPalletCodes = allList ?: arrayListOf()
            this.errorPalletCodes = errorList
            resultModel.allPalletCodes = allList ?: arrayListOf()
            resultModel.errorPalletCodes = errorList
            errorPalletCodesResultLaunch.launch(resultModel)
        } else {
            finish()
            UHFInResultLaunch.setResult(mContext, true)
        }
    }
}